package com.hulk.dryad.manage.framework.operlog;

import cn.hutool.core.util.ObjectUtil;
import com.hulk.dryad.common.component.DryadUser;
import com.hulk.dryad.common.util.SecurityUtils;
import com.hulk.dryad.common.util.WebUtils;
import jodd.util.StringPool;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 系统日志工具类
 *
 * @author hulk
 */
public class OperLogUtil {

	/**
	 * 构造 OperLogEvent
	 *
	 * @param logType OperLogType
	 * @return OPerLogEvent
	 */
	public static OperLogEvent getOperLogDTO(OperLogTypeEnum logType) {
		OperLogEvent event = new OperLogEvent();
		event.setLogType(logType.name());
		HttpServletRequest request = WebUtils.getRequest();
		String method = request.getMethod();
		// 请求信息 GET /api/test/xx
		String requestInfo = method + StringPool.SPACE + request.getRequestURI();
		// paraMap
		Map<String, String[]> paraMap = request.getParameterMap();
		if (ObjectUtil.isEmpty(paraMap)) {
			event.setParams(requestInfo);
		} else {
			StringBuilder builder = new StringBuilder(requestInfo).append(StringPool.QUESTION_MARK);
			paraMap.forEach((key, values) -> {
				builder.append(key).append(StringPool.EQUALS);
				if ("password".equalsIgnoreCase(key)) {
					builder.append("******");
				} else {
					builder.append(StringUtils.arrayToCommaDelimitedString(values));
				}
				builder.append(StringPool.AMPERSAND);
			});
			builder.deleteCharAt(builder.length() - 1);
			event.setParams(builder.toString());
		}
		// 获取请求 ip 和 ua
		event.setRequestUrl(request.getRequestURL().toString());
		event.setRequestIp(WebUtils.getIP());
		event.setHttpMethod(method);
		event.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
		// 用户信息
		DryadUser authUser = SecurityUtils.getUser();
		if (authUser != null) {
			event.setUserId(authUser.getId());
			event.setUserName(authUser.getUsername());
		}
		return event;
	}

}
